﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.Exceptions;
using HamcoWcs.Service.Common;
using HamcoWcs.Workers;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace HamcoWcs.Main.Controllers.Wcs
{
    /// <summary>
    /// 光栅操作接口
    /// </summary>
    public class RasterController : BasicController
    {
        private readonly AutomaticStorageInfo _asrs;
        private readonly ILoggerService _logger;
        /// <summary>
        /// 
        /// </summary>
        public RasterController(AutomaticStorageInfo asrs, ILoggerService logger, IMapper mapper, WcsDbContext wcsDbContext) : base(logger, mapper, wcsDbContext)
        {
            _asrs = asrs;
        }

        /// <summary>
        /// 
        /// </summary>
        public override string ControllerName => "RasterController";


        /// <summary>设置光栅Bypass</summary>
        [HttpPost]
        public IActionResult SetBypass(RasterBypassModel model, [FromHeader] string userName = "")
        {
            try
            {
                if (string.IsNullOrEmpty(model.Remark))
                    throw new WarningException("请输入备注");

                var plc = _asrs.ConveyorDic["Pcon01"];
                var raster = plc.Rasters.FirstOrDefault(x => x.Name.Equals(model.Name))
                    ?? throw new System.Exception($"未找到光栅[{model.Name}]");

                if (!plc.ConnectionStatus) return Json(ForeEndResult.Fail($"设置光栅[{model.Name}]bypass异常，连接Plc失败"));

                var r = _wcsDbContext.Rasters.FirstOrDefault(x => x.Name.Equals(model.Name));
                r.Remark = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss},{userName},{model.Remark}";
                _wcsDbContext.SaveChanges();

                raster.Remark = r.Remark;
                PconWorker.RASTER_SEND_BUFFERS.Enqueue(new RasterSendInfo()
                {
                    UserName = userName,
                    Raster = raster,
                    SetRasterStatus = false
                });
                var msg = $"{userName}屏蔽光栅，{model.Remark}";
                AddOperationLog(userName, msg, "", r.MachinePosition);
                return Json(ForeEndResult.Ok);
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (System.Exception ex)
            {
                AddSystemLog(ex.Message);
                return Json(ForeEndResult.Fail("设置时发生异常"));
            }
        }

        /// <summary>恢复光栅Bypass</summary>
        [HttpPost]
        public IActionResult ResetBypass(RasterBypassModel model, [FromHeader] string userName = "")
        {
            try
            {
                var plc = _asrs.ConveyorDic["Pcon01"];
                var raster = plc.Rasters.FirstOrDefault(x => x.Name.Equals(model.Name))
                    ?? throw new System.Exception($"未找到光栅[{model.Name}]");

                if (!plc.ConnectionStatus) return Json(ForeEndResult.Fail($"设置光栅[{model.Name}]bypass异常，连接Plc失败"));

                var r = _wcsDbContext.Rasters.FirstOrDefault(x => x.Name.Equals(model.Name));
                r.Remark = "";
                _wcsDbContext.SaveChanges();

                raster.Remark = "";
                PconWorker.RASTER_SEND_BUFFERS.Enqueue(new RasterSendInfo()
                {
                    UserName = userName,
                    Raster = raster,
                    SetRasterStatus = true
                });
                //var result = raster.ResetBypass(plc.Client);
                //if (!result) throw new System.Exception($"{userName}设置光栅Bypass失败");
                var msg = $"{userName}解除光栅屏蔽";
                AddOperationLog(userName, msg, "", r.MachinePosition);
                return Json(ForeEndResult.Ok);
            }
            catch (System.Exception ex)
            {
                AddSystemLog(ex.Message);
                return Json(ForeEndResult.Fail("恢复时发生异常"));
            }
        }
    }
}
